package com.tledu.ssm01.controller;

import com.alibaba.fastjson.JSONObject;
import com.tledu.ssm01.model.User;
import com.tledu.ssm01.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author Antg
 * @date 2021/8/12  19:08
 */
@Controller
@AllArgsConstructor
@RequestMapping("/user")
public class UserController {
    private final UserService userService;
    //用户列表
    @GetMapping("/list")
    public String list(HttpServletRequest req){
        HttpSession session = req.getSession();
        List<User> list = userService.findAll();
        session.setAttribute("userList",list);
        return "user-list";
    }

    //用户详情
    @GetMapping("/detail")
    public String detail(){
        return "user-detail";
    }

    //ajax头像上传
    @PostMapping("/upload")
    @ResponseBody
    public JSONObject uploadHeadPic(MultipartFile file,HttpServletRequest req){
        try {
            String realpath = "F:\\ideaWorkspace\\tianliangTrain\\springmvc-study\\ssm01\\src\\main\\resources\\upload";
            File file1 = new File(realpath + File.separator + file.getOriginalFilename());
            try {
                file.transferTo(file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONObject jsonObject = new JSONObject();
            String path = "/upload/" + file.getOriginalFilename();
            User user = ((User) req.getSession().getAttribute("userInfo"));
            userService.editHeadPic(user.getId(),path);
            user.setHeadPic(path);
            req.setAttribute("userInfo",user);
            jsonObject.put("url", path);
            return jsonObject;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return null;
        }
    }

    //编辑
    @PostMapping("/edit")
    public String edit(User user,HttpSession session){
        userService.editUser(user);
        User userInfo = userService.findByUserName(((User) session.getAttribute("userInfo")).getUsername());
        session.setAttribute("userInfo",userInfo);
        return "redirect:/user/list";
    }

}
